import axiosBase from 'axios';
import './cer.js';
import { Dialog, Message } from 'element-ui';

var axios = axiosBase.create({
	timeout: 1000,
});

axios.interceptors.request.use(
	function(config) {
		return config;
	},
	function(error) {
		return Promise.reject(error);
	},
);
axios.interceptors.response.use(
	function(response) {
		return response;
	},
	function(error) {
		return Promise.reject(error);
	},
);

var cer = new CER();
function getCASerialNum(pinCode, callback) {
	axios
		.get('http://localhost:9123')
		.then((res) => {
			enumdevices(pinCode, callback);
		})
		.catch((err) => {
			if (JSON.stringify(err).indexOf('ontimeout') > -1) {
				callback();
				Message.error({
					message: '您还未下载驱动，请下载并安装驱动后在进行登录',
					type: 'error',
					showClose: true})
			} else {
				enumdevices(pinCode, callback);
			}
		});
}
function enumdevices(pinCode, callback) {
	cer.enumdevices(function(res) {
		if (res.errcode == '0') {
			if (res.devices) {
				// callback(res.devices[0].serialnumber);
				for (var i = 0; i < res.errcode.length; i++) {
					verifypin(res.devices[i].manufacturer, res.devices[i].serialnumber, pinCode, callback);
				}
			} else {
				callback();
				Message.error({
					message: '未检测到CA锁，请检查是否已插入CA锁',
					type: 'error',
					showClose: true})
			}
		}
	});
}
function verifypin(_getmanufac, _getsserial, pinCode, callback) {
	setTimeout(function() {
		var _pincode = pinCode;
		//pin码
		if (_pincode == '') {
			callback();
			Message.error('PIN码不能为空');
			return;
		}

		cer.verifypin(_pincode, _getmanufac, _getsserial, function(res) {
			
			if (res.errcode == '0') {
				callback(_getsserial);
			} else {
				callback();
				Message.error('PIN码不正确');
			}
		});
	}, 0);
}

export {
	//关键
	getCASerialNum,
};
